package com.nodecollege.cloud.service.impl.deal;

import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.QueryVO;
import com.nodecollege.cloud.common.model.UnreadEvent;
import com.nodecollege.cloud.common.model.vo.ChatActiveData;
import com.nodecollege.cloud.common.utils.ThreadUserUtils;
import com.nodecollege.cloud.service.ChatService;
import com.nodecollege.cloud.service.RecordService;
import com.nodecollege.cloud.service.impl.ChatServiceAbstrat;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 第一次(或重连)初始化连接
 *
 * @author LC
 * @date 2020/2/26 23:07
 */
@Slf4j
@Service
public class ChatConnectServiceImpl extends ChatServiceAbstrat implements ChatService {

    @Autowired
    private RecordService recordService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 消息处理
     *
     * @param chatData
     * @param channel
     */
    @Override
    public void handler(String chatData, Channel channel) {
        log.info("ChatHandlerConnectServiceImpl handler");
        QueryVO<Long> queryActive = new QueryVO<>();
        queryActive.setData(ThreadUserUtils.getLoginUser().getUserId());
        List<ChatActiveData> activeDataList = recordService.getActiveChat(queryActive);
        // 给连接者返回活跃聊天信息
        sendMsg(channel, NCResult.ok(activeDataList), 3);
        // 保持用户连接状态
        connect(channel);
        for (int i = 0; i < activeDataList.size(); i++) {
            activeDataList.get(i).setUserId(queryActive.getData());
        }
        UnreadEvent unreadEvent = new UnreadEvent(this, activeDataList);
        applicationEventPublisher.publishEvent(unreadEvent);
    }

    /**
     * 未读数据反馈
     * @param activeDataList
     */
    public void unreadNum(List<ChatActiveData> activeDataList) {
        if (activeDataList.isEmpty()){
            return;
        }
        sendMsg(activeDataList.get(0).getUserId(), NCResult.ok(activeDataList), 7);
    }
}
